package com.wxw;

import org.springframework.util.StreamUtils;

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
* 网络请求工具类
* @author mumuwei
*/
public class HttpUtil {

 public static String setHttpRequest(String httpUrl, Map<String, String> params, String requestMethod) throws Exception {
   //1.定义需要访问的地址
   URL url = new URL(httpUrl);
   //2.连接URl
   HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
   //3.设置请求方式
   httpUrlConnection.setRequestMethod(requestMethod);
   //4.携带参数
   httpUrlConnection.setDoOutput(true);
   if (params != null && params.size() > 0) {
     StringBuilder sb = new StringBuilder();
     for (Map.Entry<String, String> param : params.entrySet()) {
       sb.append("&").append(param.getKey()).append("=").append(param.getValue());
     }
     httpUrlConnection.getOutputStream().write(sb.substring(1).toString().getBytes(StandardCharsets.UTF_8));
   }
   //5.发起请求
   httpUrlConnection.connect();
   //6.接受返回值
   return StreamUtils.copyToString(httpUrlConnection.getInputStream(), StandardCharsets.UTF_8);
 }

}
 